// pages/home/materialClassification/materialClassification.js
const app = getApp();
let proListToTop = [],
  menuToTop = [],
  MENU = 0,
  windowHeight, timeoutId;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    staticImg: app.globalData.staticImg,
    currentActiveIndex: 0,
    // 接口返回的商品数组
    navList: [],
    url: 'var/homeSecondShow',
    imgURL: app.globalData.imgURL, //图片总路径
    parentId: '',
    topHeight: 44,
    searchValue:'',
    // navList: [
    //   {
    //     c_id: "01",
    //     vname: '红橡'

    //   },
    //   {
    //     c_id: "02",
    //     vname: '白橡'
    //   },
    //   {
    //     c_id: "03",
    //     vname: '樱桃'
    //   },
    //   {
    //     c_id: "04",
    //     vname: '黑胡桃'
    //   },
    //   {
    //     c_id: "04",
    //     vname: '黄杨'
    //   },
    //   {
    //     c_id: "05",
    //     vname: '赤杨'
    //   },
    //   {
    //     c_id: "06",
    //     vname: '枫木'
    //   },
    //   {
    //     c_id: "07",
    //     vname: '白蜡'
    //   },
    // ],

  },

  changeMenu(e) {
    console.log(e.target.id);
    // 改变左侧tab栏操作
    if (Number(e.target.id) === this.data.currentActiveIndex) return
    MENU = 1
    this.setData({
      currentActiveIndex: Number(e.target.id),
      rightProTop: proListToTop[Number(e.target.id)]
    })
    this.setMenuAnimation(Number(e.target.id))
  },
  scroll(e) {
    console.log("滚动:",e.detail.scrollTop);
    console.log("proListToTop:", proListToTop);
    for (let i = 0; i < proListToTop.length; i++) {
      if (e.detail.scrollTop < proListToTop[i] && i !== 0 && e.detail.scrollTop > proListToTop[i - 1]) {
        console.log("scrollTop:", e.detail.scrollTop);
        console.log("i:",i);
        console.log("proListToTop【"+i+"】",proListToTop[i]);
        return this.setDis(i)
      } else if (e.detail.scrollTop > proListToTop[proListToTop.length-1]){
        return this.setDis(proListToTop.length)
      }
    }
    // 找不到匹配项，默认显示第一个数据
    if (!MENU) {
      this.setData({
        currentActiveIndex: 0
      })
    }
    MENU = 0
  },
  setDis(i) {
    // 设置左侧menu栏的选中状态
    var that = this;
    console.log("设置菜单选中:",i);
    console.log("当前选中:", that.data.currentActiveIndex);
    if (i != that.data.currentActiveIndex+1 && !MENU) {
      that.setData({
        currentActiveIndex: i - 1
      })
    }
    MENU = 0
    if(i==menuToTop.length){
      i--;
    }
    that.setMenuAnimation(i)
  },
  setMenuAnimation(i) {
    // 设置动画，使menu滚动到指定位置。
    console.log("menuToTop:",menuToTop);
    console.log("menuToTop【"+i+"】:",menuToTop[i]);
    let self = this
    if (menuToTop[i].animate) {
      // 节流操作
      if (timeoutId) {
        clearTimeout(timeoutId)
      }
      timeoutId = setTimeout(() => {
        console.log(12138)
        self.setData({
          leftMenuTop: (menuToTop[i].top - windowHeight)
        })
      }, 50)
    } else {

      if (this.data.leftMenuTop === 0) return

      this.setData({
        leftMenuTop: 0
      })
    }
  },
  getActiveReacts() {
    wx.createSelectorQuery().selectAll('.menu-active').boundingClientRect(function(rects) {
      return rects[0].top
    }).exec()
  },


  getAllRects() {
    var that = this;
    proListToTop.length = 0;
    menuToTop.length = 0;
    // 获取商品数组的位置信息
    wx.createSelectorQuery().selectAll('.pro-item').boundingClientRect(function(rects) {
      console.log("rects:", rects)
      rects.forEach(function(rect) {
        console.log("rect:", rect)
        // 这里减去44是根据你的滚动区域距离头部的高度，如果没有高度，可以将其删去
        proListToTop.push(rect.top - that.data.topHeight);
      })
      console.log("初始化加载 proListToTop:", proListToTop.length);
    }).exec()





    // 获取menu数组的位置信息
    wx.createSelectorQuery().selectAll('.menu-item').boundingClientRect(function(rects) {
      wx.getSystemInfo({
        success: function(res) {
          console.log(res);
          windowHeight = res.windowHeight / 2
          // console.log(windowHeight)
          rects.forEach(function(rect) {
            menuToTop.push({
              top: rect.top,
              animate: rect.top > windowHeight
            })
          })
        }
      })
    }).exec()
  },
  // 获取系统的高度信息
  getSystemInfo() {
    let self = this;
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        windowHeight = res.windowHeight / 2
        var topHeight = 88 / 750 * res.windowWidth;
        console.log("顶部预留宽度:" + topHeight);
        that.setData({
          topHeight: topHeight,
        })
      }
    })
  },
  imgHeight: function(e) {
    console.log("图片高度" + e.detail.height);
    console.log("图片宽度" + e.detail.width);
  },
  imgClick: function(e) {
    var that = this;
    console.log(e.currentTarget.id)
    wx.previewImage({
      urls: [that.data.imgURL + e.currentTarget.id],
    })
  },

  searchProducts:function(event){
    var that = this;
    console.log("搜索：", that.data.searchValue);
    app.post(that.data.url, {
      'parentId': that.data.parentId,
      'context': that.data.searchValue
    }).then((res) => {
      console.log('success');
      console.log(res);
      if (res.code == 0) {
        that.setData({
          navList: res.resultData,
        })
        setTimeout(() => {
          that.getAllRects();
        }, 200)
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.msg,
          showCancel: false,
        })
      }
    }).catch((errMsg) => {
      console.log('fail');
      console.log(errMsg + '失败');
    })

  },
  inputSearch(event){
    console.log("event.detail.value：",event.detail.value);
    var that = this;
    that.setData({
      searchValue:event.detail.value,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    // 确保页面数据已经刷新完毕~
    var parentId = options.varid;
    var isSearch = options.search;
    if(isSearch){
      return;
    }
    that.setData({
      parentId:parentId,
    })
    
    that.getSystemInfo();
    app.post(that.data.url, {
      'parentId': parentId
    }).then((res) => {
      console.log('success');
      console.log(res);
      if (res.code == 0) {
        // var resultList = res.resultData;
        // if(resultList!=null&&resultList.length>0){
        //   for(var i=0;i<resultList.length;i++){
        //     var nPInfo = resultList[i].ThirdVariety;
        //     console.log("nPinfo",nPInfo)
        //     nPInfo.imgUrl = nPInfo.imgUrl.split(',');
        //   }
        // }

        that.setData({
          navList: res.resultData,
        });
        setTimeout(() => {
          that.getAllRects();
        }, 500)
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.msg,
          showCancel: false,
        })
      }
    }).catch((errMsg) => {
      console.log('fail');
      console.log(errMsg + '失败');
    })



  },

  splictImgUrl:function(imgUrl){
    var imgUrlArray = [];
    if(imgUrl==null||imgUrl.length==0){
      return [];
    }
    imgUrlArray = imgUrl.split(",");
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})